package com.cungmua.app.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.cungmua.app.R;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

/**
 * Created by kelvin.nguyen on 6/16/14.
 */
public class AppUtils {
    private static SimpleDateFormat dateFormatter;
    private static SimpleDateFormat dateShowFormatter;
    private static SimpleDateFormat dateFormatterSimple;
    private static SimpleDateFormat showDateFormatter;



    public static Integer tryParse(String text) {
        try {
            return new Integer(text);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    public final static boolean isValidEmail(CharSequence target) {
        if (target == null) {
            return false;
        } else {
            return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
        }
    }

    @SuppressLint("SimpleDateFormat")
    public static SimpleDateFormat getServerTimeFormatter() {
        if (dateFormatter == null) {
            dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            dateFormatter.setTimeZone(TimeZone.getTimeZone("gmt"));
        }
        return dateFormatter;
    }

    public static String convertMillis(long millis) {
        String hms = String.format(
                "%02d:%02d:%02d",
                TimeUnit.MILLISECONDS.toHours(millis),
                TimeUnit.MILLISECONDS.toMinutes(millis)
                        - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
                        .toHours(millis)),
                TimeUnit.MILLISECONDS.toSeconds(millis)
                        - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
                        .toMinutes(millis)));
        return hms;
    }

    public static SimpleDateFormat getShowDateFormatter() {
        if (showDateFormatter == null) {
            showDateFormatter = new SimpleDateFormat("MMM dd, yyyy");
        }
        return showDateFormatter;
    }

    public static SimpleDateFormat getShowTimeFormatter() {
        if (dateShowFormatter == null) {
            dateShowFormatter = new SimpleDateFormat("hh:mm a");
        }
        return dateShowFormatter;
    }

    public static int parseFullPriceString(String price) {
        price = price.replaceAll("[.,]", "");
        return Integer.parseInt(price);
    }

    public static String getFullPriceString(int price) {
        DecimalFormat formatter = new DecimalFormat("###,###,###");
        formatter.setDecimalFormatSymbols(new DecimalFormatSymbols(
                Locale.ENGLISH));
        return formatter.format(price);
    }

    public static String getPriceString(int price) {
        if (price < 100000) {
            DecimalFormat formatter = new DecimalFormat("###,###,###");
            return formatter.format(price);
        } else {
            // Round down to thousand
            price = price - (price % 1000);
            DecimalFormat formatter = new DecimalFormat("###,###,###.###");
            return formatter.format(price / 1000000.0);
        }
    }

    public static String getPriceUnitString(Context context, int price) {
        Resources r = context.getResources();
        if (price < 100000) {
            return r.getString(R.string.small_price_unit);
        } else {
            return r.getString(R.string.price_unit);
        }
    }

    public static String getDayDifference(long time) {
        long timeDiff = time - System.currentTimeMillis();
        if (timeDiff < 0)
            return "0 ";

        long dayDiff = timeDiff / (1000L * 60 * 60 * 24);
        return String.valueOf(dayDiff) + " ";
    }

    public static long getMilisDifference(long time) {
        long timeDiff = time - System.currentTimeMillis();
        if (timeDiff < 0)
            return 0;
        return timeDiff;
    }

    public static String getTimeDifference(long time) {
        long timeDiff = time - System.currentTimeMillis();
        if (timeDiff < 0)
            return "00:00:00";
        timeDiff = timeDiff % (1000L * 60 * 60 * 24);
        timeDiff = timeDiff - (3600000 * 7);

        return convertMillis(timeDiff);
    }

    public static String getRelativeTimeSpanString(Context context, long time) {
        Resources r = context.getResources();
        long timeDiff = System.currentTimeMillis() - time;
        if (timeDiff < 60000) { // under a minute
            timeDiff = timeDiff / 1000;
            return r.getString(R.string.span_second, timeDiff);
        } else if (timeDiff < 1000L * 60 * 60) { // under an hour
            timeDiff = timeDiff / 1000 / 60;
            return r.getString(R.string.span_minute, timeDiff);
        } else if (timeDiff < 1000L * 60 * 60 * 24) { // under a day
            timeDiff = timeDiff / 1000 / 60 / 60;
            return r.getString(R.string.span_hour, timeDiff);
        } else if (timeDiff < 1000L * 60 * 60 * 24 * 30) { // under a month
            timeDiff = timeDiff / 1000 / 60 / 60 / 24;
            return r.getString(R.string.span_day, timeDiff);
        } else if (timeDiff < 1000L * 60 * 60 * 24 * 30 * 12) { // under a year
            timeDiff = timeDiff / 1000 / 60 / 60 / 24 / 30;
            return r.getString(R.string.span_month, timeDiff);
        } else {
            timeDiff = timeDiff / 1000 / 60 / 60 / 24 / 30 / 12;
            return r.getString(R.string.span_year, timeDiff);
        }
    }

    public static Date parseServerTime(String string) throws ParseException {
        SimpleDateFormat inFormat = AppUtils.getServerTimeFormatter();
        return inFormat.parse(string);
    }

    public static Date parseServerDate(String date) throws ParseException {
        SimpleDateFormat inFormat = AppUtils.getServerDateFormatter();
        return inFormat.parse(date);
    }

    public static SimpleDateFormat getServerDateFormatter() {
        if (dateFormatterSimple == null) {
            dateFormatterSimple = new SimpleDateFormat("MM/dd/yyyy");
            dateFormatterSimple.setTimeZone(TimeZone.getTimeZone("gmt"));
        }
        return dateFormatterSimple;
    }

    public static String MD5(String source) {
        source = source.trim().toLowerCase();
        Log.d("sign", source);
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(source.getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
        }
        return null;
    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            if (listItem instanceof ViewGroup) {
                listItem.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            }
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }






    public static String replaceNull(String input) {
        return ((input== null) ? "" : input);
    }
}
